import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SpUtil {
  static final SpUtil _instance = SpUtil._internal();
  factory SpUtil() => _instance;
  SpUtil._internal();

  SharedPreferences? _prefs;

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // 保存数据
  Future<bool> save(String key, dynamic value) {
    if (_prefs == null) throw Exception('SharedPreferences 未初始化');
    debugPrint('${value.runtimeType}');
    switch (value.runtimeType) {
      case String:
        return _prefs!.setString(key, value);
      case int:
        return _prefs!.setInt(key, value);
      case double:
        return _prefs!.setDouble(key, value);
      case bool:
        return _prefs!.setBool(key, value);
      case const (List<String>):
        return _prefs!.setStringList(key, value);
      default:
        throw Exception('不支持的存储类型');
    }
  }

  // 读取数据
  dynamic get(String key) => _prefs?.get(key);

  String getString(String key, {String defValue = ''}) =>
      _prefs?.getString(key) ?? defValue;

  int getInt(String key, {int defValue = 0}) =>
      _prefs?.getInt(key) ?? defValue;

  double getDouble(String key, {double defValue = 0.0}) =>
      _prefs?.getDouble(key) ?? defValue;

  bool getBool(String key, {bool defValue = false}) =>
      _prefs?.getBool(key) ?? defValue;

  List<String> getStringList(String key, {List<String> defValue = const []}) =>
      _prefs?.getStringList(key) ?? defValue;

  // 删除数据
  Future<bool> remove(String key) async =>
      _prefs?.remove(key) ?? Future.value(false);

  Future<bool> clear() async => _prefs?.clear() ?? Future.value(false);
}